/**
 *    Copyright 2009 Thomas Johnson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weareriot.hitprox;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.mortbay.servlet.ProxyServlet;

public class HitboxSnooperProxyServlet extends ProxyServlet {
	private HitProxUI ui;
	
	public HitboxSnooperProxyServlet(HitProxUI ui) {
		super();
		this.ui = ui;
		
	}

	public void service(ServletRequest request,
			ServletResponse response) throws ServletException, IOException {
		super.service(request, response);
	
			HttpServletRequest req = (HttpServletRequest) request;
			System.out.println(">>> REQ: " + request.getServerName());
			if(request.getServerName().toLowerCase().contains("hitbox")) {
				if(req.getMethod().equalsIgnoreCase("CONNECT")) {
					System.out.println(">>> CONNECT (SSL): " + req.getRequestURI());
				} else {
					System.out.println(">>> PROXY: " + req.getRequestURI() + " Args: " + req.getQueryString());
					String queryString = req.getQueryString();
					HashMap<String, String> params = processQueryString(queryString);
					System.out.println("vcon: " + params.get("vcon"));
					System.out.println("n: " +  params.get("n"));
					
					ui.addEvent(params);
				}
			}
	}

	/**
	 * Explodes a query string into a map of name-value pairs.
	 * 
	 * If multiple values are specified, the last one wins. If a value is not given, it is
	 * replaced with null. No URLdecoding is performed at this time.
	 * 
	 * @param queryString
	 * @return
	 */
	private HashMap<String, String> processQueryString(String queryString) {
		HashMap<String,String> params = new HashMap<String,String>();
		if(queryString == null || queryString.trim().equals("")) return params;
		
		for(String s : queryString.split("&")) {
			String[] prop = s.split("=");
			
			assert prop.length == 1 || prop.length == 2 : "Expected 1 or 2 tokens from (param)[=(value)], but found " + prop.length + " tokens";
			
			if(prop.length == 1) {
				params.put(prop[0], null);
			} else {
				try {
					params.put(prop[0], java.net.URLDecoder.decode(prop[1], "UTF-8"));
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException("UTF-8 is not a supported encoding for URLDecoder", e);
				}
			}
		}
		return params;
	}
}
